﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TrickingLibrary.Data;
using TrickingLibrary.Models;

namespace TrickingLibrary.Api.Controllers
{
    [ApiController]
    [Route("api/difficulties")]
    public class DifficultyController:ControllerBase
    {
        private readonly AppDbContext _ctx;

        public DifficultyController(AppDbContext ctx)
        {
            _ctx = ctx;
        }

        [HttpGet]
        public IEnumerable<Difficulty> All() => _ctx.Difficulties.ToList();

        [HttpGet("{id}")]
        public Difficulty Get(string id) => _ctx.Difficulties
            .FirstOrDefault(x => x.Id.Equals(id,
                StringComparison.InvariantCultureIgnoreCase));


        [HttpGet("{Id}/tricks")]
        public IEnumerable<Trick> ListDifficultyTricks(string Id) =>
            _ctx.Tricks
                .Where(x => x.DifficultyId.Equals(Id, StringComparison.InvariantCultureIgnoreCase))
                .ToList();
                

        [HttpPost]
        public async Task<Difficulty> Create([FromBody] Difficulty difficulty)
        {
            difficulty.Id = difficulty.Name.Replace(" ", "-").ToLowerInvariant();
            _ctx.Add(difficulty);
            await _ctx.SaveChangesAsync();
            return difficulty;
        }


        [HttpPut]
        public async Task<Difficulty> Update([FromBody] Difficulty difficulty)
        {
            if(string.IsNullOrEmpty(difficulty.Id))
            {
                return null;
            }

            _ctx.Add(difficulty);
            await _ctx.SaveChangesAsync();
            return difficulty;
        }


        [HttpDelete("{id}")]
        public async Task<IActionResult> Delete(string id)
        {
            var difficulty = _ctx.Difficulties.FirstOrDefault(x => x.Id.Equals(id));
            difficulty.Deleted = true;
            await _ctx.SaveChangesAsync();
            return Ok();
        }
        
    }
}